package com.lipei.vrp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Vrp {
	public String name;
	public String comment;
	public String type;
	public int dimension;
	public String weight_type;
	public int capacity;
	public ArrayList<VrpData> data;
	private final static Pattern pattern = Pattern.compile("\\d+");

	public static Vrp vrpReader(String filename) throws IOException {
		File file = new File(filename);
		if (!file.exists()) {
			return null;
		}

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				new FileInputStream(file)));

		ArrayList<String> lines = new ArrayList<String>();
		while (true) {
			String line = reader.readLine();

			if (line == null) {
				break;
			}
			lines.add(line);
		}

		Vrp vrp = new Vrp();

		vrp.name = lines.get(0).substring(7);
		vrp.comment = lines.get(1).substring(10);
		vrp.type = lines.get(2).substring(7);
		vrp.dimension = Integer.parseInt(lines.get(3).substring(12));
		vrp.weight_type = lines.get(4).substring(18);
		vrp.capacity = Integer.parseInt(lines.get(5).substring(11));

		vrp.data = new ArrayList<VrpData>();
		int i = 7;
		for (; i < lines.size(); i++) {
			String line = lines.get(i);
			if (line.startsWith("DEMAND_SECTION")) {
				break;
			}
			VrpData vrpdata = new VrpData();
			vrp.data.add(vrpdata);

			Matcher match = pattern.matcher(line);

			match.find();
			match.find();

			vrpdata.xcoord = Integer.parseInt(match.group());

			match.find();
			vrpdata.ycoord = Integer.parseInt(match.group());
		}
		i++;
		for (int index = 0; i < lines.size(); i++, index++) {
			String line = lines.get(i);
			if (line.startsWith("DEPOT_SECTION")) {
				break;
			}
			VrpData vrpdata = vrp.data.get(index);

			Matcher match = pattern.matcher(line);

			match.find();
			match.find();

			vrpdata.demand = Integer.parseInt(match.group());

		}

		return vrp;
	}
}
